package controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.KeywordUnique;
import server.Get;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@SuppressWarnings("serial")
public class CheckServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setCharacterEncoding("utf-8");
		
		String google = req.getParameter("google").trim();
		String title = req.getParameter("title").trim().replaceAll("[\\|]+$", "");
		String domain = req.getParameter("domain").trim();
		
		String[] arrGoogle = google.split(" ");
		String[] arrTitle = title.split("\\|");
		
		HashMap<String,String> listGoogle = new HashMap<String,String>();
		
		for (int i = 0; i < arrTitle.length; i++) {
			listGoogle.put(arrTitle[i], arrGoogle[i]);
		}

		String str = req.getParameter("name");

		str = URLDecoder.decode(str,"UTF-8");

		String[] arr = new String[listGoogle.size()];
		
		PutCache.putCacheList(str, "view",30);
		
		new Get(str,listGoogle,arr);

		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		req.setAttribute("arr", arr);
		req.setAttribute("listGoogle", listGoogle);
		req.setAttribute("domain", domain);
		
		try {
			ObjectifyService.register(KeywordUnique.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		Objectify objectify = ObjectifyService.begin();
		try {
			KeywordUnique keyword = objectify.get(new Key<KeywordUnique>(KeywordUnique.class, str));
		} catch (Exception e) {
			KeywordUnique key = new KeywordUnique();
			key.setName(str);
			
			objectify.put(key);
		}
		
		try {
			req.getRequestDispatcher("/check.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}